package com.boge.springframework.support;

import com.boge.springframework.ApplicationContext;
import com.boge.springframework.beans.BeansException;
import com.boge.springframework.beans.factory.ApplicationContextAware;
import com.boge.springframework.beans.factory.config.BeanPostProcessor;

/***
 * 包装ApplicationContextAwareProcessor
 * 目的：让继承自 ApplicationContextAware的Bean感知到applicationContext属性
 * BeanPostProcessor: 是为了在 createBean初始化的时候执行 postProcessBeforeInitialization 从而调用 Aware的方法
 * 因此,需要createBean初始化的时候去执行
 */
public class ApplicationContextAwareProcessor implements BeanPostProcessor {

    private final ApplicationContext applicationContext;

    public ApplicationContextAwareProcessor(ApplicationContext applicationContext) {
        this.applicationContext = applicationContext;
    }

    @Override
    public Object postProcessBeforeInitialization(Object bean, String beanName) throws BeansException {
        if (bean instanceof ApplicationContextAware){
            ((ApplicationContextAware) bean).setApplicationContext(applicationContext);
        }
        return bean;
    }

    @Override
    public Object postProcessAfterInitialization(Object bean, String beanName) throws BeansException {
        return bean;
    }
}

  